﻿using UnityEngine;
using UnityEngine.UI;

public class PrefabBall : MonoBehaviour {

	public GameObject ballPrefab;
	public bool status = true;	//游戏进行
	public int number = 20;		//小球剩余数
	public BallUp lastBall;	//最后一个小球
	public GameObject music2;


	// Use this for initialization
	void Start () {
		music2 = GameObject.Find ("Music");
		
	}
	
	// Update is called once per frame
	void Update () {
		if (!status) {
			return;
		}
		if (number > 0) {

			if (Input.GetKeyDown (KeyCode.Mouse0)) {
				GameObject bullet = Instantiate (ballPrefab) as GameObject;
				bullet.GetComponent<MeshRenderer> ().material.color = RandomColor ();
				lastBall = bullet.GetComponent<BallUp>();
				number--;
			}
			if (number <= 2) {
				if (GameObject.Find ("Ball" + number) != null) {
					GameObject.Find ("Ball" + number).SetActive (false);
					GameObject.Find ("T" + number).SetActive (false);
				}
			}
			for (int i = 0; i < (number > 2 ? 3 : number); i++) {
				GameObject.Find ("T" + i).GetComponent<Text> ().text = (number - i).ToString ();
			}
		} else {
			if (!lastBall.status) {
				music2.SendMessage ("Music2Play");
				Invoke ("OnWinWin",1f);
				status = false;
			}
		}
	}

	void Reset(int level)
	{
		number = 5 + 2 * ((level-1) / 6);
	}

	Color RandomColor()
	{
		float r = Random.Range (0f,1f);
		float g = Random.Range (0f,1f);
		float b = Random.Range (0f,1f);
		Color color = new Color (r,g,b);
		return color;
	}

	void OnStop()
	{
		status = false;
	}

	void OnWinWin()
	{
		transform.GetComponent<LevelUp> ().OnWin ();
	}
}
